package cfdt.ldl.web.service.account;


import cfdt.common.exception.CodeException;
import cfdt.common.vo.ObjectBaseResponse;
import cfdt.ldl.core.entity.UserInfo;
import cfdt.ldl.core.system.SystemConstants;
import cfdt.ldl.sys.api.feign.SysFeign;
import cfdt.ldl.sys.api.request.LoginSysRequest;
import cfdt.ldl.web.api.request.LoginWebRequest;
import cfdt.ldl.web.api.response.LoginWebResponse;
import cfdt.ldl.web.api.vo.UserInfoLessVO;
import cfdt.ldl.web.helper.TokenSessionHelper;
import cfdt.ldl.web.util.WebTokenUtil;
import cn.hutool.core.bean.BeanUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.HashMap;
import java.util.Map;

@Service
public class LoginWebService {

    @Autowired
    SysFeign sysFeign;
    @Autowired
    private TokenSessionHelper tokenSessionHelper;

    /**
     * 登录
     */
    public ObjectBaseResponse<LoginWebResponse> login(@RequestBody LoginWebRequest loginWebRequest) throws CodeException {
        // TODO 登录校验

        // 调用用户中心进行登录
        LoginSysRequest loginSysRequest = new LoginSysRequest();
        BeanUtil.copyProperties(loginWebRequest, loginSysRequest);
        ObjectBaseResponse<UserInfo> loginResponse = sysFeign.doLogin(loginSysRequest);
        // 登录成功
        UserInfo userInfo = loginResponse.checkAndGetData();
        // 生成token
        String token = WebTokenUtil.generateToken(userInfo.getSystemNo(), SystemConstants.secret);
        // 将登录信息加入到redis
        refreshLoginUser(userInfo, token);

        // 对象转换
        UserInfoLessVO userInfoLessVO = new UserInfoLessVO();
        BeanUtil.copyProperties(userInfo, userInfoLessVO);
        // 响应成功
        LoginWebResponse loginWebResponse = LoginWebResponse.builder().token(token).userInfo(userInfoLessVO).build();
        return ObjectBaseResponse.success(loginWebResponse);
    }

    /**
     * 刷新登录用户信息加入redis
     * 这个地方融资云会加入菜单权限，此项目不涉及菜单权限，先不要处理
     *
     * @param userInfo
     * @param token
     */
    protected void refreshLoginUser(UserInfo userInfo, String token) {
        Map<String, Object> redisValMap = new HashMap<>();
        redisValMap.put("Token", token);
        redisValMap.put("User", userInfo);
        tokenSessionHelper.addTokenSession(userInfo.getSystemNo(), redisValMap);
    }
}
